import { HttpService } from '@nestjs/axios';
import { ConfigService } from '@nestjs/config';
import { Injectable, HttpStatus, HttpException, HttpCode, Logger } from '@nestjs/common';
import { OnlyofficeService } from '../onlyoffice/onlyoffice.service';
import { defaultAxiosConfig } from 'src/common/utils';
import { OnlyHttpService } from 'src/shared/only-http/only-http.service';
import { lastValueFrom } from 'rxjs';
import { ApiPath } from 'src/common/api';
import { JwtService } from '@nestjs/jwt';
import { FileMangerService } from 'src/shared/file-manger/file-manger.service';
import { UserInfoModel } from 'src/common/model/res-common';
import axios from 'axios';
import { writeFile } from 'fs/promises';
import { cloneDeep } from 'lodash';
import { OnlyofficeEditorConfig } from 'src/onlyoffice/config.default';
import { Request } from 'express';

@Injectable()
export class DocumentService {
  constructor(
    private readonly config: ConfigService,
    private onlyofficeService: OnlyofficeService,
    // private readonly redisService: RedisService,
    private readonly httpService: OnlyHttpService,
    private readonly jwt: JwtService,
    private readonly fileManger: FileMangerService,
  ) {}
  // 获取默认配置
  getOnlyofficeConfigInfo = async (
    filePath: string,
    fileKey: string,
    fileName: string,
    userInfo: UserInfoModel,
    type: 1 | 2 = 1,
  ): Promise<OnlyofficeEditorConfig> => {
    const editorConfig = this.onlyofficeService.editorDefaultConfig();
    // 添加文档
    editorConfig.document = {
      ...editorConfig.document,
      fileType: 'docx',
      key: fileKey,
      url: `${this.config.get('domain')}/${filePath}`,
      title: fileName,
    };
    // 添加用户信息
    const user = {
      group: userInfo.LAB_ID,
      id: userInfo.USER_NO,
      name: userInfo.USER_NAME,
    };
    editorConfig.editorConfig.user = user;
    // 添加插件配置
    if (userInfo && type === 1) {
      editorConfig.editorConfig.plugins = {
        autostart: [this.config.get('GUID')],
        pluginsData: [`${this.config.get('domain')}/static/plugins/custom/config.json`],
      };
    }
    // 加密编辑器参数
    if (userInfo) {
      this.onlyofficeService.signJwt(editorConfig);
    }
    return editorConfig;
  };
  // 获取文件配置
  // @params type 1-插件编辑  2-模版编辑
  getUrlDocAndConfig = async (req: Request, type: 1 | 2 = 1) => {
    // const urlParams = new URLSearchParams(req.);
    const urlQuery = req.query;
    const formVerId = urlQuery.form_ver_id || '';
    const token = urlQuery?.access_token as string;
    const pgroupId = urlQuery?.pgroup_id || '';
    const formId = urlQuery?.form_id;
    const refreshToken = urlQuery?.refresh_token;
    if (!token) {
      return Promise.reject('token 未配置');
    }

    const params = { form_ver_id: formVerId, browse_type: '1' };
    const header = { Authorization: 'Bearer ' + token };
    // console.log('header', urlQuery);
    const resData = await this.httpService.get<string>(ApiPath.Tim.GetWorkFormVerFile, { params, headers: header });
    let fileUrl = resData.data;
    // 维护过表单
    if (fileUrl?.length > 0) {
      const userInfo = this.jwt.decode(token, { json: true }) as UserInfoModel;
      const uId = cloneDeep(token).split('.').pop();
      const fName = cloneDeep(fileUrl).split('/').pop();
      const fPath = await this.fileManger.getTempPathWithName(uId, fName);
      // download
      const resData = await axios.get(fileUrl, { responseType: 'stream', ...defaultAxiosConfig });
      await writeFile(fPath, resData.data);
      const fileKey = await this.fileManger.getFileKey(uId, fName);
      const rPath = await this.fileManger.getTempRelativePathWithName(uId, fName);
      const cusConfig = await this.getOnlyofficeConfigInfo(rPath, fileKey, fName, userInfo, type);
      Logger.log(cusConfig, 'cusConfig');

      return cusConfig;
    }
    return Promise.reject('no config');
  };
  // 编辑模版文件文件配置
  getTemplateAndConfig = async (req: Request) => {
    // const urlParams = new URLSearchParams(req.);
    const urlQuery = req.query;
    const formVerId = urlQuery.form_ver_id || '';
    const token = urlQuery?.access_token as string;
    const pgroupId = urlQuery?.pgroup_id || '';
    const headerId = urlQuery?.header_id;
    let headerFile = urlQuery?.header_file as string;
    const refreshToken = urlQuery?.refresh_token;
    if (!token) {
      return Promise.reject('token 未配置');
    }
    // //  空白模版
    // if (!headerFile || headerFile?.length == 0) {
    //   headerFile = '/public/template/empty.docx';
    // }
    // 维护过
    // if (headerFile) {
    const userInfo = this.jwt.decode(token, { json: true }) as UserInfoModel;
    const upName = cloneDeep(token).split('.').pop();
    const uId = upName + `@ver_id${formVerId}.@file_id${headerId}.`;
    const fName = cloneDeep(headerFile).split('/').pop();
    const fPath = await this.fileManger.getTempPathWithName(uId, fName);
    // download
    const resData = await axios.get(headerFile, { responseType: 'stream', ...defaultAxiosConfig });
    await writeFile(fPath, resData.data);

    const fileKey = await this.fileManger.getFileKey(uId, fName);
    const rPath = await this.fileManger.getTempRelativePathWithName(uId, fName);
    const cusConfig = await this.getOnlyofficeConfigInfo(rPath, fileKey, fName, userInfo, 2);
    Logger.log(cusConfig, 'cusConfig');

    return cusConfig;
    // }
    // return Promise.reject('no config');
    // 未维护过,需要新建
  };
  // 选择模版文件文件配置
  getSelectTemplateAndConfig = async (req: Request) => {
    // const urlParams = new URLSearchParams(req.);
    const urlQuery = req.query;
    const formVerId = urlQuery.form_ver_id || '';
    const token = urlQuery?.access_token as string;
    const pgroupId = urlQuery?.pgroup_id || '';
    const headerId = urlQuery?.header_id;
    const headerFile = urlQuery?.header_file as string;
    const refreshToken = urlQuery?.refresh_token;
    if (!token) {
      return Promise.reject('token 未配置');
    }
    if (!headerFile) {
      return Promise.reject('模版文件未找到');
    }
    // 读取模版文件
    const userInfo = this.jwt.decode(token, { json: true }) as UserInfoModel;
    const upName = cloneDeep(token).split('.').pop();
    const uId = upName + `@ver_id${formVerId}.@file_id${headerId}.`;
    const fNameList = cloneDeep(headerFile).split('/');
    const fName = fNameList?.[fNameList.length - 1];
    const fPath = await this.fileManger.getTempPathWithName(uId, fName);
    // download
    const resData = await axios.get(headerFile, { responseType: 'stream', ...defaultAxiosConfig });
    await writeFile(fPath, resData.data);
    const fileKey = await this.fileManger.getFileKey(uId, fName);
    const rPath = await this.fileManger.getTempRelativePathWithName(uId, fName);
    const cusConfig = await this.getOnlyofficeConfigInfo(rPath, fileKey, fName, userInfo, 1);
    Logger.log(cusConfig, 'getSelectTemplateAndConfig');

    return cusConfig;
  };
}
